﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Data.EntityClient;

using HelpCentral.Configuration;
using HelpCentral.Shared.Security;
using HelpCentral.Shared.Interfaces;
using HelpCentral.Data.Model;

namespace HelpCentral.Data.Repository
{
    public class UserRepository : IUserRepository
    {
        HelpCentralModelContainer context = ContextContainer.Instance;

        #region IUserRepository Members

        protected IQueryable<User> UserWithIncludes()
        {
            return context.User.Include("Client").Include("AuditEvents");
        }

        public IUser FetchUserById(int userId)
        {
            return UserWithIncludes().FirstOrDefault(x => x.UserId == userId).FromRepositoryObject();
        }

        public IUser FetchUserByUsername(int? clientId, string username)
        {
            return UserWithIncludes().FirstOrDefault(x => x.Username == username && ((clientId == null && x.Client == null) || (clientId != null && x.Client.ClientId == clientId))).FromRepositoryObject();
        }

        public IUser FetchUserByADUsername(int? clientId, string adUsername)
        {
            return UserWithIncludes().FirstOrDefault(x => x.ADUsername == adUsername && ((clientId == null && x.Client == null) || (clientId != null && x.Client.ClientId == clientId))).FromRepositoryObject();
        }

        public IEnumerable<IUser> FetchUsersByClientId(int? clientId)
        {
            return UserWithIncludes().Where(x => (clientId == null && x.Client == null) || (clientId != null && x.Client.ClientId == clientId)).AsEnumerable().Select(x => x.FromRepositoryObject());
        }

        public IUser CommitUser(IUser user)
        {
            var u = user.ToRepositoryObject(context);

            if (u.EntityState == System.Data.EntityState.Detached)
            {
                context.User.AddObject(u);
            }

            context.SaveChanges();

            return u.FromRepositoryObject();
        }

        #endregion
    }
}
